import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

import {blocks as mockBlocks} from '@/mocks/blocks';
import type {Block} from '@/types/Block';

export const useEditorStore = defineStore('editor', () => {
  const blocks=ref<Block[]>(mockBlocks)

  const addBlock=(block:Block)=>{
    console.log("block",block);
    
    blocks.value.push(block)
  }
  const updateBlocks=(newBlocks:Block[])=>{
    blocks.value=newBlocks
  }

  const activeBlockId=ref<string|null>(null)

  const selectBlock=(block:Block)=>{
    activeBlockId.value=block.id
  }

  const selectedBlock=computed(()=>{
    return blocks.value.find(block=>block.id===activeBlockId.value)||null
  })

  const updateBlock=(block:Block)=>{
    const index=blocks.value.findIndex(b=>b.id===block.id)
    if(index!==-1){
      blocks.value.splice(index,1,block)
    }
  }

  return{
    activeBlockId,
    blocks,
    selectedBlock,
    addBlock,
    updateBlocks,
    selectBlock,
    updateBlock
  }
})

